package com.dong.controller;

import com.alibaba.fastjson.JSON;
import com.dong.untils.ReceiveObject;
import com.dong.pojo.User;
import com.dong.untils.ResponseBean;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;

@Controller
public class CommunicationController {
    @Autowired
    private HttpServletRequest httpRequest;

    @RequestMapping(value = "/communication" ,produces ="application/json;charset=utf-8")
    @ResponseBody
    public ResponseBean<?> send_response() throws IOException {
        System.out.println("进入通信了");
        //读取客户端请求携带的json字符串
        String jsonRequest = "";
        jsonRequest = receivePost(httpRequest);

        //响应给客户端
        ResponseBean<Object> response = new ResponseBean<Object>();
        //StringBuffer result = new StringBuffer();
        User user1 = new User(1, "启动设备", "123456", "允许");
        ArrayList<User> list = new ArrayList<>();
        list.add(user1);
        //Java对象 转 JSON字符串
        String str1 = JSON.toJSONString(list);
        response.setSuccess(true);
        response.setCode("0");
        response.setDesc("OK");
        //response.setResult(result.toString().substring(0, result.toString().length() - 1));
        response.setResult(str1);
        return response;
    }

    //获取请求的内容
    protected String receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
        String reqBody = "";
        try {
            // 读取请求内容
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            reqBody = sb.toString();
            ReceiveObject receiveObject1 = JSON.parseObject(reqBody, ReceiveObject.class);
            String str1 = JSON.toJSONString(receiveObject1);
            System.out.println(receiveObject1);
        } catch (Exception e) {
            System.out.printf("e");
        }
        return reqBody;
    }
}
